<template>
  <div
    ref="wrapper"
    class="max-dialog__wrapper"
    :class="visible ? '' : 'hidden'"
  >
    <div class="max-dialog" :style="`margin-top: ${top}; width: ${width}`">
      <div class="max-dialog__header">
        <span class="max-dialog_title">{{ title }}</span>
        <slot name="title"></slot>
        <button
          class="max-dialog__headerbtn"
          v-show="showClose"
          @click="handleClose"
        >
          <i class="max-dialog__close el-icon el-icon-close"></i>
        </button>
      </div>
      <div class="max-dialog__body">
        <slot></slot>
      </div>
      <div class="max-dialog__footer">
        <slot name="footer"></slot>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "max-diolog",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
    },
    width: {
      type: String,
      default: "50%",
    },
    top: {
      type: String,
      default: "15vh",
    },
    showClose: {
      type: Boolean,
      default: true,
    },
    beforeClose: {
      type: Function,
    },
  },
  data() {
    return {};
  },
  mounted() {
    this.init();
  },
  beforeDestroy() {
    this.$refs["wrapper"].removeEventListener("click", this.handleWrapperClick);
  },
  methods: {
    init() {
      this.$refs["wrapper"].addEventListener("click", this.handleWrapperClick);
    },
    handleWrapperClick(e) {
      const target = e.target || e.srcElement;
      if (target === this.$refs["wrapper"]) {
        this.handleClose();
      }
    },
    handleClose() {
      this.beforeClose();
      this.$emit("close");
    },
  },
};
</script>

<style lang="less">
.max-dialog__wrapper {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  overflow: auto;
  margin: 0;
  visibility: visible;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 20;

  &.hidden {
    visibility: hidden;
  }
}

.max-dialog {
  position: relative;
  box-sizing: border-box;
  width: 50%;
  margin: 0 auto;
  border-radius: 2px;
  background-color: #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
}

.max-dialog__header {
  padding: 20px 20px 10px 20px;
}

.max-dialog__headerbtn {
  position: absolute;
  top: 20px;
  right: 20px;
  padding: 0;
  background: 0 0;
  border: none;
  outline: none;
  cursor: pointer;
  font-size: 16px;
}

.max-dialog__body {
  padding: 30px 20px;
  color: #606266;
  font-size: 14px;
  word-break: break-all;
}
</style>
